package controller.user;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.role.RoleService;
import cn.smbms.service.role.RoleServiceImpl;
import cn.smbms.service.user.UserService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;
import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @program: SMBMS-two
 * @description:
 * @author: Mr.peng
 * @create: 2020-05-23 17:19
 **/
@Controller
public class Users {
   ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
   UserService userService=context.getBean("user", UserService.class);
    String name;
//     @Resource
//     UserService userService;

// @RequestMapping("/jsp/user.do")
//    public String doPost(HttpServletRequest request, HttpServletResponse response)
//            throws ServletException, IOException {
//        String method = request.getParameter("method");
//        System.out.println("method----> " + method);
//        if(method != null && method.equals("add")){
//            //增加操作
//            this.add();
//        }else if(method != null && method.equals("query")){
//            this.query(request, response);
//        }else if(method != null && method.equals("getrolelist")){
//            this.getRoleList(request, response);
//        }else if(method != null && method.equals("ucexist")){
//            this.userCodeExist(request, response);
//        }else if(method != null && method.equals("deluser")){
//            this.delUser(request, response);
//        }else if(method != null && method.equals("view")){
//            this.getUserById(request, response,"jsp/userview");
//        }else if(method != null && method.equals("modify")){
//            this.getUserById(request, response,"jsp/usermodify");
//        }else if(method != null && method.equals("modifyexe")){
//           // this.modify(request, response);
//        }else if(method != null && method.equals("pwdmodify")){
//            this.getPwdByUserId(request, response);
//        }else if(method != null && method.equals("savepwd")){
//            this.updatePwd(request, response);
//        }
//        return name;
//    }
    @RequestMapping("/jsp/userupdate.do")
    private String updatePwd(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Object o = request.getSession().getAttribute(Constants.USER_SESSION);
        String newpassword = request.getParameter("newpassword");
        boolean flag = false;
        if(o != null && !StringUtils.isNullOrEmpty(newpassword)){
            //UserService userService = new UserServiceImpl();
            flag = userService.updatePwd(((cn.smbms.pojo.User)o).getId(),newpassword);
            if(flag){
                request.setAttribute(Constants.SYS_MESSAGE, "修改密码成功,请退出并使用新密码重新登录！");
                request.getSession().removeAttribute(Constants.USER_SESSION);//session注销
            }else{
                request.setAttribute(Constants.SYS_MESSAGE, "修改密码失败！");
            }
        }else{
            request.setAttribute(Constants.SYS_MESSAGE, "修改密码失败！");
        }
       // request.getRequestDispatcher("pwdmodify.jsp").forward(request, response);
        return "login";
    }

    @RequestMapping(value = "/jsp/userPwd.do",method = RequestMethod.GET,produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    private Object getPwdByUserId(HttpServletRequest request)
            throws ServletException, IOException {
        Object o = request.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = request.getParameter("oldpassword");
        HashMap<String, String> resultMap = new HashMap<String, String>(16);
        if(null == o ){//session过期
            resultMap.put("result", "sessionerror");
        }else if(StringUtils.isNullOrEmpty(oldpassword)){//旧密码输入为空
            resultMap.put("result", "error");
        }else{
            String sessionPwd = ((cn.smbms.pojo.User)o).getUserPassword();
            System.out.println("密碼++++++++++++++"+sessionPwd);
            if(oldpassword.equals(sessionPwd)){
                resultMap.put("result", "true");
            }else{//旧密码输入不正确
                resultMap.put("result", "false");
            }
        }
       // response.setContentType("application/json");
//        PrintWriter outPrintWriter = response.getWriter();
//        outPrintWriter.write(JSONArray.toJSONString(resultMap));
//        outPrintWriter.flush();
//        outPrintWriter.close();
          return JSONArray.toJSONString(resultMap);
    }

    @RequestMapping("/jsp/usermodify.do")
    private String modify(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id = request.getParameter("uid");
        String userName = request.getParameter("userName");
        String gender = request.getParameter("gender");
        String birthday = request.getParameter("birthday");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        String userRole = request.getParameter("userRole");
        cn.smbms.pojo.User user = new cn.smbms.pojo.User();
        user.setId(Integer.valueOf(id));
        user.setUserName(userName);
        user.setGender(Integer.valueOf(gender));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.valueOf(userRole));
        user.setModifyBy(((cn.smbms.pojo.User)request.getSession().getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());

        //UserService userService = new UserServiceImpl();
        if(userService.modify(user)){
            //response.sendRedirect(request.getContextPath()+"/jsp/user.do?method=query");
            return "redirect:/jsp/user.do";
          //  query(request, response);
        }else{
            //request.getRequestDispatcher("usermodify.jsp").forward(request, response);
            return  "usermodify";
        }

    }
    @RequestMapping("/jsp/userview.do")
    private String getUserById(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id = request.getParameter("uid");
        String url=null;
        String method=request.getParameter("method");
        if(method.equals("view")){
            url="jsp/userview";
        }else if(method.equals("modify")){
            url="jsp/usermodify";
        }
        if(!StringUtils.isNullOrEmpty(id)){
            //调用后台方法得到user对象
            // UserService userService = new UserServiceImpl();
            cn.smbms.pojo.User user = userService.getUserById(id);
            request.setAttribute("user", user);
            //request.getRequestDispatcher(url).forward(request, response);
            return url;
        }
        return null;
    }
    @RequestMapping("/jsp/userdeluser.do")
    private void delUser(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id = request.getParameter("uid");
        Integer delId = 0;
        try{
            delId = Integer.parseInt(id);
        }catch (Exception e) {
            // TODO: handle exception
            delId = 0;
        }
        HashMap<String, String> resultMap = new HashMap<String, String>();
        System.out.println("+++++++++++++++++"+delId);
        if(delId <= 0){
            resultMap.put("delResult", "notexist");
        }else{
            //UserService userService = new UserServiceImpl();
            if(userService.deleteUserById(delId)){
                resultMap.put("delResult", "true");
            }else{
                resultMap.put("delResult", "false");
            }
        }

        //把resultMap转换成json对象输出
        response.setContentType("application/json");
        PrintWriter outPrintWriter = response.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush();
        outPrintWriter.close();
    }

    @RequestMapping("/jsp/userucexist.do")
    private void userCodeExist( HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //判断用户账号是否可用
        String userCodes = request.getParameter("userCode");
        System.out.println("___________"+userCodes);
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if(StringUtils.isNullOrEmpty(userCodes)){
            //userCode == null || userCode.equals("")
            resultMap.put("userCode", "exist");
        }else{
            //UserService userService = new UserServiceImpl();
            cn.smbms.pojo.User user = userService.selectUserCodeExist(userCodes);
            if(null != user){
                resultMap.put("userCode","exist");
            }else{
                resultMap.put("userCode", "notexist");
            }
        }

        //把resultMap转为json字符串以json的形式输出
        //配置上下文的输出类型
        response.setContentType("application/json");
        //从response对象中获取往外输出的writer对象
        PrintWriter outPrintWriter = response.getWriter();
        //把resultMap转为json字符串 输出
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush();//刷新
        outPrintWriter.close();//关闭流
    }
    @RequestMapping("/jsp/usergetrolelist.do")
    @ResponseBody
    private Object getRoleList(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<Role> roleList = null;
        RoleService roleService = new RoleServiceImpl();
        roleList = roleService.getRoleList();
        //把roleList转换成json对象输出
//        response.setContentType("application/json");
//        PrintWriter outPrintWriter = response.getWriter();
//        outPrintWriter.write(JSONArray.toJSONString(roleList));
//        outPrintWriter.flush();
//        outPrintWriter.close();
        return JSONArray.toJSONString(roleList);
    }

    @RequestMapping("/jsp/user.do")
    private String query(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //查询用户列表
        String queryUserName = request.getParameter("queryname");
        String temp = request.getParameter("queryUserRole");
        String pageIndex = request.getParameter("pageIndex");
        int queryUserRole = 0;
        //UserService userService = new UserServiceImpl();
        List<cn.smbms.pojo.User> userList = null;
        //设置页面容量
        int pageSize = Constants.pageSize;
        //当前页码
        int currentPageNo = 1;

        /**
         * http://localhost:8090/SMBMS/userlist.do
         * ----queryUserName --NULL
         * http://localhost:8090/SMBMS/userlist.do?queryname=
         * --queryUserName ---""
         */
        System.out.println("queryUserName servlet--------"+queryUserName);
        System.out.println("queryUserRole servlet--------"+queryUserRole);
        System.out.println("query pageIndex--------- > " + pageIndex);
        if(queryUserName == null){
            queryUserName = "";
        }
        if(temp != null && !temp.equals("")){
            queryUserRole = Integer.parseInt(temp);
        }

        if(pageIndex != null){
            try{
                currentPageNo = Integer.valueOf(pageIndex);
            }catch(NumberFormatException e){
               // response.sendRedirect("error.jsp");
                 return "error";
            }
        }
        //总数量（表）
        int totalCount	= userService.getUserCount(queryUserName,queryUserRole);
        System.out.println("数量"+totalCount);
        //总页数
        PageSupport pages=new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);

        int totalPageCount = pages.getTotalPageCount();
        System.out.println(totalPageCount);
        //控制首页和尾页
        if(currentPageNo < 1){
            currentPageNo = 1;
        }else if(currentPageNo > totalPageCount){
            currentPageNo = totalPageCount;
        }

        userList = userService.getUserList(queryUserName,queryUserRole,currentPageNo, pageSize);
        request.setAttribute("userList", userList);
        List<Role> roleList = null;
        RoleService roleService = new RoleServiceImpl();
        roleList = roleService.getRoleList();
        request.setAttribute("roleList", roleList);
        request.setAttribute("queryUserName", queryUserName);
        request.setAttribute("queryUserRole", queryUserRole);
        request.setAttribute("totalPageCount", totalPageCount);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("currentPageNo", currentPageNo);
       // request.getRequestDispatcher("userlist.jsp").forward(request, response);
         return "jsp/userlist";
    }
//    @RequestMapping("/jsp/useradd.do")
//    private String add(HttpServletRequest request,
//                       @RequestParam(value = "a_idPicPath",required = false) MultipartFile attach,
//                       HttpSession session)
//            throws ServletException, IOException {
//        System.out.println("add()================");
//        String idpath=null;
//        //判断文件是否为空
//        if (!attach.isEmpty()){
//            String path=request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");
//            System.out.println("path===="+path);
//            String name=attach.getOriginalFilename(); //原文件名
//            System.out.println("name===="+name);
//            String prefix= FilenameUtils.getExtension(name);  //原文件名后缀
//            System.out.println("prefix============="+prefix);
//            int filesize=500000;
//            if(attach.getSize()>filesize){//上传文件不得大于500kb
//                request.setAttribute("uploadfiles","*上传文件大小不得超过500kb");
//                return "jsp/useradd";
//            }else if(prefix.equalsIgnoreCase("jpg")||prefix.equalsIgnoreCase("png")
//                    ||prefix.equalsIgnoreCase("jpeg")||prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
//                String filename=System.currentTimeMillis()+ Math.abs(new Random().nextLong()) +"_Personal.jsp";
//                System.out.println("new filename============"+attach.getName());
//                File targetFile=new File(path,filename);
//                if (!targetFile.exists()){
//                    targetFile.mkdirs();
//                }
//                //保存
//                try{
//                    attach.transferTo(targetFile);
//                }catch (Exception e){
//                    e.printStackTrace();
//                    request.setAttribute("uploadFileError","*上传失败！");
//                    return "jsp/useradd";
//                }
//                idpath=path+File.separator+filename;
//            }else{
//                request.setAttribute("uploadFileError","* 上传图片格式不正确");
//                return "jsp/useradd";
//            }
//        }
//        String userCode = request.getParameter("userCode");
//		String userName = request.getParameter("userName");
//		String userPassword = request.getParameter("userPassword");
//		String gender = request.getParameter("gender");
//		String birthday = request.getParameter("birthday");
//		String phone = request.getParameter("phone");
//		String address = request.getParameter("address");
//		String userRole = request.getParameter("userRole");
//        cn.smbms.pojo.User user = new cn.smbms.pojo.User();
//        user.setUserCode(userCode);
//		user.setUserName(userName);
//		user.setUserPassword(userPassword);
//		user.setAddress(address);
//		user.setIdPicPath(idpath);
//        //复制，扣匹
//       // BeanUtils.copyProperties(model,user);
//        try {
//            //user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(two.getBirthday()));
//            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
//        } catch (ParseException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//        //User loggeruser=((cn.smbms.pojo.User)session.getAttribute(Constants.USER_SESSION));
////         if (loggeruser==null){
////             return "redirect:login";
////         }
//        user.setCreationDate(new Date());
//        user.setGender(Integer.valueOf(gender));
//		user.setPhone(phone);
//        user.setCreatedBy(((User)request.getSession().getAttribute(Constants.USER_SESSION)).getId());
//         //user.setCreatedBy(loggeruser.getId());
//        //UserService userService = new UserServiceImpl();
//        boolean gs=userService.add(user);
//        if(gs){
//            //response.sendRedirect(request.getContextPath()+"/jsp/user.do?method=query");
//            return "redirect:/jsp/user.do";
//        }else{
//            //request.getRequestDispatcher("useradd.jsp").forward(request, response);
//             return "jsp/useradd";
//        }
//    }
    @RequestMapping("/jsp/useradd.do")
    public String provideradd(HttpServletRequest request,
                              @RequestParam(value = "attachs",required = false)
                                      MultipartFile[] attachs) throws IOException,Exception {
        String userCode = request.getParameter("userCode");
        String userName = request.getParameter("userName");
        String userPassword = request.getParameter("userPassword");
        String gender = request.getParameter("gender");
        String birthday = request.getParameter("birthday");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        String userRole = request.getParameter("userRole");
        String idPiaPath = null;
        String errorinfo = null;
        String workPicPath = null;
        boolean fog = true;
        String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "imgs");
        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()) {
                if (i == 0) {
                    errorinfo = "uploadFileError";
                } else {
                    errorinfo = "uploadWpError";
                }
                System.out.println("uploadFile path=========>" + path);
                String oldFileName = attach.getOriginalFilename();
                System.out.println("uploadFile oldFileName========>" + oldFileName);
                String prefix = FilenameUtils.getExtension(oldFileName);
                System.out.println("uploadFile prefix========>" + prefix);
                int filesize = 500000;
                System.out.println("uploadFile size==========>" + attach.getSize());
                if (attach.getSize() > filesize) {
                    request.setAttribute("errorinfo", "* 上传文件不得超过500KB");
                    fog = false;
                } else if (prefix.equalsIgnoreCase("jpg")
                        || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg")
                        || prefix.equalsIgnoreCase("pneg")) {
                    String fileName = System.currentTimeMillis() + Math.abs(new Random().nextLong()) + ".jpg";
                    System.out.println(fileName);
                    System.out.println("new fileName==========>" + attach.getName());
                    File targetFile = new File(path,fileName);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }
                    try {
                        attach.transferTo(targetFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute("errorinfo", "* 上传失败");
                        fog = false;
                    }
                    if (i == 0) {
                        idPiaPath = path + File.separator + fileName;
                    } else if (i == 1) {
                        workPicPath = path + File.separator + fileName;
                    }
                    System.out.println(idPiaPath);
                    System.out.println(workPicPath);
                } else {
                    request.setAttribute("errorinfo", "* 上传图片格式不正确");
                    fog = false;
                }
            }
        }
        cn.smbms.pojo.User user = new cn.smbms.pojo.User();
        user.setUserRole(Integer.parseInt(userRole));
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setAddress(address);
        user.setCreationDate(new Date());
        user.setGender(Integer.valueOf(gender));
        try {
            //user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(two.getBirthday()));
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //User loggeruser=((cn.smbms.pojo.User)session.getAttribute(Constants.USER_SESSION));
//         if (loggeruser==null){
//             return "redirect:login";
//         }
        user.setPhone(phone);
        user.setCreatedBy(((User) request.getSession().getAttribute(Constants.USER_SESSION)).getId());
        user.setIdPicPath(idPiaPath);
        boolean flag = false;
        if (fog) {
            flag = userService.add(user);
            if (flag) {
                return "redirect:/jsp/user.do";
            }
        }
        return "jsp/useradd";
    }
}
